package patrol.mobile.com.mobilepatrol.api;

import android.os.Handler;
import android.os.Message;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.bean.ResultInfo;

/**
 * Created by 健 on 2014/9/7.
 */
public class DataUtil {
    private static Gson gson=new Gson();

    private static void GetData(final PatrolApp ac, final String url, final String requestMode, final Handler handler,
                                final Map<String,Object> params, final Map<String,File> files) {
        new Thread(){
            @Override
            public void run() {
                Message msg = new Message();
                try {
                    ResultInfo result= ApiClient.getResultInfo(ac,url,requestMode,params,files);

                    if(result!=null){
                        if (result.getCode() == ResultInfo.CODE_SUCCESS) {
                            msg.what = MyHandler.MSG_SUCCESS;
                            msg.obj = result.getValue();
                        }else{
                            msg.what = MyHandler.MSG_FAILURE;
                            msg.obj = result.getMessage();
                        }
                    }else{
                        msg.what=MyHandler.MSG_FAILURE;
                        msg.obj=ac.getString(R.string.connect_server_failure);
                    }

                } catch (AppException e) {
                    e.printStackTrace();
                    msg.what =MyHandler.MSG_ERR;
                    msg.obj = e;
                }

                handler.sendMessage(msg);
            }
        }.start();
    }

    public static<T> T parseJsonInfo(String jsonStr,Class<T> classOfT){
        T jsonInfo=null;
        try {
            jsonInfo = gson.fromJson(jsonStr, classOfT);
        }catch (Exception e){
            e.printStackTrace();
        }
        return jsonInfo;
    }

//    /**
//     * 上传 巡道信息
//     * @param ac
//     * @param toJson
//     */
//    public static void uploadPatrolInfo(PatrolApp ac,Handler handler, String toJson) {
//        Map<String,Object> param=new HashMap<String,Object>();
//        param.put("type","PatrolInfoBean");
//        param.put("json",toJson);
//        GetData(ac, getUrl(ac,R.string.url_info_upload), ApiClient.REQ_POST, handler, param, null);
//    }

    /**
     * 上传 路况调查信息
     * @param ac
     * @param handler
     * @param toJson
     */
    public static void uploadInvestInfo(PatrolApp ac,Handler handler, String toJson){
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("type","TrafficInvestBaseInfo");
        param.put("json",toJson);
        GetData(ac, getUrl(ac, R.string.url_info_upload), ApiClient.REQ_POST, handler, param, null);
    }

//    /**
//     * 上传地理位置信息
//     * @param ac
//     * @param handler
//     * @param toJson
//     */
//    public static void uploadLocationInfo(PatrolApp ac,Handler handler,String toJson){
//        Map<String,Object> param=new HashMap<String,Object>();
//        param.put("type","locationInfo");
//        param.put("json",toJson);
//        GetData(ac, getUrl(ac,R.string.url_info_upload), ApiClient.REQ_POST, handler, param, null);
//    }
    private static String getUrl(PatrolApp ac,int resId){
        StringBuilder sb=new StringBuilder();
        sb.append(ac.getString(R.string.url_http_head));
        sb.append(ac.getServerHost());
        sb.append(ac.getString(resId));

        return sb.toString();
    }

    /**
     * 初始化 所有数据
     * @param ac
     * @param handler
     * @param type
     */
    public static void initData(PatrolApp ac, Handler handler, String type) {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("type",type);
        GetData(ac, getUrl(ac,R.string.url_info_download), ApiClient.REQ_GET, handler, param, null);

      /*  Message msg = new Message();
        msg.what = MyHandler.MSG_SUCCESS;
        msg.obj = "{\"cars\":[{\"carNumber\":\"新A36058\",\"iD\":\"1\",\"org_No\":1},{\"carNumber\":\"新A454815\",\"iD\":\"2\",\"org_No\":2}],\"org\":[{\"org_Name\":\"昌吉州公路管理局\",\"org_No\":1,\"org_Number\":\"1\"},{\"org_Name\":\"昌吉分局\",\"org_No\":2,\"org_Number\":\"2\"},{\"org_Name\":\"阜康分局\",\"org_No\":3,\"org_Number\":\"3\"},{\"org_Name\":\"吉木萨尔分局\",\"org_No\":4,\"org_Number\":\"4\"},{\"org_Name\":\"呼图壁分局\",\"org_No\":5,\"org_Number\":\"5\"},{\"org_Name\":\"玛纳斯分局\",\"org_No\":6,\"org_Number\":\"6\"},{\"org_Name\":\"木垒分局\",\"org_No\":7,\"org_Number\":\"7\"},{\"org_Name\":\"奇台分局\",\"org_No\":8,\"org_Number\":\"8\"},{\"org_Name\":\"硫磺沟分局\",\"org_No\":9,\"org_Number\":\"9\"}],\"route\":[{\"endPot\":\"K30+980\",\"manageiD\":\"1\",\"org_No\":2,\"routeiD\":\"111\",\"routeName\":\"G360\",\"startPot\":\"K2+500\"},{\"endPot\":\"K20+600\",\"manageiD\":\"2\",\"org_No\":2,\"routeiD\":\"be891c22-baf2-40f1-9218-d987a8fda46c\",\"routeName\":\"S216\",\"startPot\":\"K1+000\"}],\"task\":[{\"detailInfoBeans\":[{\"endPot\":\"K200+30\",\"endPotKm\":200,\"endPotMeter\":30,\"iD\":\"1\",\"routeiD\":\"111\",\"routeName\":\"G360\",\"startPot\":\"K100+20\",\"startPotKm\":100,\"startPotMeter\":20,\"taskiD\":\"1\"},{\"endPot\":\"K30+500\",\"endPotKm\":30,\"endPotMeter\":500,\"iD\":\"3\",\"routeiD\":\"be891c22-baf2-40f1-9218-d987a8fda46c\",\"routeName\":\"S216\",\"startPot\":\"K20+100\",\"startPotKm\":20,\"startPotMeter\":100,\"taskiD\":\"1\"}],\"iD\":\"1\",\"org_No\":6,\"taskName\":\"2014年第一次调查\"},{\"detailInfoBeans\":[{\"endPot\":\"K200+30\",\"endPotKm\":200,\"endPotMeter\":30,\"iD\":\"2\",\"routeiD\":\"111\",\"routeName\":\"G360\",\"startPot\":\"K100+20\",\"startPotKm\":100,\"startPotMeter\":20,\"taskiD\":\"2\"}],\"iD\":\"2\",\"org_No\":2,\"taskName\":\"2014年第一次调查\"},{\"detailInfoBeans\":[],\"iD\":\"3\",\"org_No\":3,\"taskName\":\"2014年第一次调查\"},{\"detailInfoBeans\":[],\"iD\":\"4\",\"org_No\":4,\"taskName\":\"2014年第一次调查\"},{\"detailInfoBeans\":[],\"iD\":\"5\",\"org_No\":5,\"taskName\":\"2014年第一次调查\"}],\"user\":[{\"iD\":1,\"orgName\":\"昌吉州公路管理局\",\"org_No\":1,\"userName\":\"admin\"},{\"iD\":2,\"orgName\":\"昌吉分局\",\"org_No\":2,\"userName\":\"张兴平\"},{\"iD\":6,\"orgName\":\"昌吉分局\",\"org_No\":2,\"userName\":\"张三\"}]}";
        handler.sendMessage(msg);*/

    }

//    /**
//     * 上传 巡道明细照片信息
//     * @param ac
//     * @param handler
//     * @param id
//     * @param imgFiles
//     */
//    public static void uploadPatrolItemImageInfo(PatrolApp ac, Handler handler, String id, List<File> imgFiles) {
//        Map<String,Object> param=new HashMap<String,Object>();
//        param.put("bizID",id);
//
//        Map<String,File> files=new HashMap<String,File>();
//        String key="img";
//        int index=0;
//        for(File f:imgFiles){
//            files.put(key+String.valueOf(index++),f);
//        }
//        GetData(ac, getUrl(ac,R.string.url_img_upload), ApiClient.REQ_POST, handler, param, files);
//
//    }
//    public static List<File> getPatrolDetailImageFile(PatrolApp ac,PatrolDetailInfoBean infoBean){
//        List<File> imgFiles=new ArrayList<File>();
//        if(!StringUtils.isEmpty(infoBean.getPhotoNumber())) {
//            String[] imageNames = infoBean.getPhotoNumber().split(",");
//            for (String imageName : imageNames) {
//                File f = new File(ac.getImageSavePath() + File.separator + imageName);
//                if (f.exists())
//                    imgFiles.add(f);
//            }
//        }
//
//        return imgFiles;
//    }

    /**
     * 初始化 调查数据
     * @param ac
     * @param handler
     * @param orgNo
     */
    public static void initStructData(final PatrolApp ac, final Handler handler, final String orgNo) {
        final List<LinkedTreeMap> data = new ArrayList<LinkedTreeMap>();
        final int[] productCount = new int[1];
        final int pageSize=5000;

        final Handler dataBatchHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
            	if(msg==null){
           		 Message message = new Message();
                    message.what = MyHandler.MSG_FAILURE;
                    message.obj = "当前机构没有对应的调查数据!";
                    handler.sendMessage(message);
                    return;
	           	}
	           	if(msg.obj==null){
	          		 Message message = new Message();
	                   message.what = MyHandler.MSG_FAILURE;
	                   message.obj = "当前机构没有对应的调查数据!";
	                   handler.sendMessage(message);
	                   return;
	           	}
                if (msg.what == 1) {
                    data.addAll((java.util.Collection<? extends LinkedTreeMap>) msg.obj);

                   // List<RouteSurveyTaskDataBO> dt = gson.fromJson(str,new TypeToken<List<RouteSurveyTaskDataBO>>(){}.getType());

                  //  data.addAll(dt);//将加载数据加到商品数值后面
                    synchronized (productCount) {
                        if (data.size() == productCount[0]) {//是否已经加载完
                            Message message = new Message();
                            message.what = MyHandler.MSG_SUCCESS;
                            message.obj = data;
                            handler.sendMessage(message);
                        } else {
//                            Message message2 = new Message();
//                            message2.what = MyHandler.MSG_PAGE;
                            int page=data.size()/pageSize+1;
//                            handler.sendMessage(message2);
                            loadStructDataByBatch(ac, orgNo, this, page,pageSize);
                        }
                    }
                } else {
                    Message message = new Message();
                    message.copyFrom(msg);
                    handler.sendMessage(message);
                }
            }
        };
        Handler dataCountHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    try {
                        productCount[0] = new JSONObject(msg.obj.toString()).getInt("surveyDatacount");
                    } catch (JSONException e) {
                        e.printStackTrace();
                        return;
                    }
                    loadStructDataByBatch(ac, orgNo,dataBatchHandler, 1,pageSize);
                } else {
                    Message message = new Message();
                    message.copyFrom(msg);
                    handler.sendMessage(message);
                }
            }
        };
        loadDataCount(ac, dataCountHandler, orgNo);
    }
    public static void loadDataCount(PatrolApp ac, Handler handler, String orgNo) {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("type","surveyDatacount");
        param.put("orgNo",orgNo);
        GetData(ac, getUrl(ac,R.string.url_info_download), ApiClient.REQ_GET, handler, param, null);
    }
    private static void loadStructDataByBatch(PatrolApp ac, String orgNo, Handler handler, int pageNo, int pageSize){
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("type","surveyData");
        param.put("pageNo",pageNo);
        param.put("pageSize",pageSize);
        param.put("orgNo",orgNo);
        GetData(ac, getUrl(ac,R.string.url_info_download), ApiClient.REQ_GET, handler, param, null);

    }

    public static void checkVersion(PatrolApp ac, Handler handler, int curVersionCode) {
        Map<String,Object> param=new HashMap<String,Object>();
        param.put("version", curVersionCode);
        param.put("type","version");
        GetData(ac, getUrl(ac,R.string.url_info_download), ApiClient.REQ_GET, handler, param, null);
    }
}
